package com.ssy.lingxi.logistics.handler.listener;

import cn.hutool.core.util.StrUtil;
import com.rabbitmq.client.Channel;
import com.ssy.lingxi.common.utils.ObjectSerializableUtil;
import com.ssy.lingxi.logistics.api.constans.LogisticsServiceConstants;
import com.ssy.lingxi.logistics.api.dto.queue.LogisticsMessageQueueDTO;
import com.ssy.lingxi.logistics.api.enums.LogisticsMessageQueueTypeEnum;
import com.ssy.lingxi.logistics.service.IMessageQueueHandleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 物流服务消息监听类
 * @author wyx
 * @version 2.0.0
 * @date 2022-03-10
 **/
@Component
public class MessageQueueListener {
    private final static Logger log = LoggerFactory.getLogger(MessageQueueListener.class);
    private final static Logger logger = LoggerFactory.getLogger(MessageQueueListener.class);

    @Resource
    private IMessageQueueHandleService messageQueueHandleService;


    /**
     * 消息处理
     * @param message 消息
     * @param channel 消息通道
     */
    @RabbitListener(queues = LogisticsServiceConstants.LOGISTICS_SERVICE_QUEUE, ackMode = "MANUAL")
    public void handler(Message message, Channel channel) {
        try {
            String jsonMessage = new String(message.getBody());
            logger.info("内部物流服务消息队列接收到消息 =>" + jsonMessage);

            LogisticsMessageQueueDTO queueDTO = ObjectSerializableUtil.deserialize(jsonMessage, LogisticsMessageQueueDTO.class);
            if (queueDTO == null || StrUtil.isEmpty(queueDTO.getMessage())) {
                logger.info("内部物流服务消息反序列化错误 =>" + jsonMessage);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
                return;
            }

            LogisticsMessageQueueTypeEnum messageType = LogisticsMessageQueueTypeEnum.parse(queueDTO.getType());
            switch (messageType) {
                case SYNC_LOGISTICS_ADDRESS:
                    messageQueueHandleService.syncLogisticsAddress(queueDTO.getMessage());
                    break;
                case DELETE_LOGISTICS_ADDRESS:
                    messageQueueHandleService.deleteLogisticsAddress(queueDTO.getMessage());
                    break;
                case UPDATE_LOGISTICS_ADDRESS_STATUS:
                    messageQueueHandleService.updateLogisticsAddressStatus(queueDTO.getMessage());
                    break;
                default:
                    break;
            }

            //确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (Exception e) {
            logger.error("内部物流服务消息队列接收消息错误 =>" + e.getMessage());
        }
    }
}
